/*
 * @Author: wenqingwu
 * @Date: 2022-01-14 15:20:38
 * @LastEditTime: 2022-04-01 15:03:24
 * @LastEditors: WenQingwu
 * @Description: 系统管理、权限、角色模块
 * @FilePath: \doctormanage\routes\SystemRouter.js
 */

const express = require("express");
const router = express.Router();
const db = require('./../db/config');
const msgJson = require('./msgJson')
module.exports = router;


/**
 * 1. 添加权限接口
 * @param {String} accessName  权限名称,required
 * @param {String} accessDes 权限描述,required
 */
router.route("/addAccess")
  .post((req, res) => {

    let checkResult = msgJson.checkParam(req.body, ['accessName', 'accessDes']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }
    let { accessName, accessDes } = req.body;
    let sql = 'insert into accesscontrol (acname,acdes) values(?,?);';
    let param = [accessName, accessDes];
    let cb = (err) => {
      if (!err) {
        res.json(msgJson.requestSuccess('添加权限'))
      } else {
        res.json(msgJson.requestFail('添加权限', err.sqlMessage))
      }
    }

    db.connect(sql, param, cb)
  });


/**
 * 2.查询所有权限接口,查询指定权限
 * @param {String} searchText,搜索权限的名称，支持模糊查询
 */
router.route('/getAccess')
  .get((req, res) => {
    let { searchText } = req.query;
    if (searchText === undefined) {
      res.json(paramIsRequired('searchText'))
    }
    let sql = 'select * from accesscontrol';
    let param = [];
    if (searchText.trim().length !== 0) {
      sql += ' where acname like ?;'
      param.push('%' + searchText + '%')
    } else {
      sql += ";"
    }

    let cb = (err, data) => {
      if (!err) {
        res.json(msgJson.requestSuccess('获取权限列表', data))
      } else {
        res.json(msgJson.requestFail('获取权限列表', err.sqlMessage))
      }
    }
    db.connect(sql, param, cb)
  });


/**
 *  3. 删除权限
 * @param {string} acid, 权限ID，required.
 */
router.route('/delAccess')
  .post((req, res) => {
    let checkResult = msgJson.checkParam(req.body, ['acid']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }

    let { acid } = req.body;
    // number类型判断
    if (typeof acid !== "number") {
      acid = Number(acid);
      if (isNaN(acid)) {
        res.json(msgJson.paramOfType('acid'))
        return;
      }
    }
    let sql = 'delete from accesscontrol where acid = ?;'
    let param = [acid];
    let cb = (err, data) => {
      if (!err) {
        res.json(msgJson.requestSuccess('删除权限操作'))
      } else {
        res.json(msgJson.requestFail('删除权限操作', err.sqlMessage))
      }
    }
    db.connect(sql, param, cb)
  });

/**
 *  4. 添加角色
 * @param {String} r_name,角色名称 required
 * @param {String} r_des, 角色描述 required
 */

router.route('/addRole')
  .post((req, res) => {
    let checkResult = msgJson.checkParam(req.body, ['r_name', 'r_des']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }

    const { r_name, r_des } = req.body;

    let sql = 'insert into role (r_name,r_des) values (?,?);';
    let param = [r_name, r_des];
    let cb = (err, data) => {
      if (!err) {
        res.json(msgJson.requestSuccess('添加角色'));
      } else {
        res.json(msgJson.requestFail('添加角色', err.sqlMessage));
      }
    }
    db.connect(sql, param, cb);

  });

/**
 *  5.获取角色、搜索角色
 * @param {String} r_name,角色名称，required. 允许为空字符。
 * @returns {Array} 查询的结果，一个数组
 */
router.route('/getRole')
  .get((req, res) => {
    const { searchText } = req.query;
    console.log(searchText)
    if (searchText === undefined) {
      res.json(paramIsRequired('searchText'))
    }
    let sql = 'SELECT * FROM role';
    let param = [];
    if (searchText.trim().length !== 0) {
      sql += ' where r_name like ?;'
      param.push('%' + searchText + '%')
    } else {
      sql += ";"
    }

    let cb = (err, data) => {
      if (!err) {
        res.json(msgJson.requestSuccess('获取角色列表', data))
      } else {
        res.json(msgJson.requestFail('获取角色列表', err.sqlMessage))
      }
    }
    console.log(sql, param)
    db.connect(sql, param, cb)
  });

/**
 *  6. 删除角色
 * @param {string} r_id, 角色ID，required.
 */
router.route('/delRole')
  .post((req, res) => {

    let checkResult = msgJson.checkParam(req.body, ['r_id']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }
    let { r_id } = req.body;
    // number类型判断
    if (typeof r_id !== "number") {
      r_id = Number(r_id);
      if (isNaN(r_id)) {
        res.json(msgJson.paramOfType('r_id'));
        return;
      }
    }
    let sql = 'delete from role where r_id = ?;'
    let param = [r_id];
    let cb = (err, data) => {
      if (!err) {
        res.json(msgJson.requestSuccess('删除角色操作'))
      } else {
        res.json(msgJson.requestFail('删除角色操作', err.sqlMessage))
      }
    }
    db.connect(sql, param, cb)
  });

/**
 * 7. 修改角色状态
 * @param {string} r_id, 角色ID，required.如:'123'
 */
router.route('/modifyAccessState')
  .post((req, res) => {
    let checkResult = msgJson.checkParam(req.body, ['r_id', 'r_state']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }
    let { r_id, r_state } = req.body;
    // number类型判断
    if (typeof r_id !== "number") {
      r_id = Number(r_id);
      if (isNaN(r_id)) {
        res.json(msgJson.paramOfType('r_id'))
        return;
      }
    }

    let sql = 'update role set r_state = ? where r_id = ?;';
    let param = [r_state, r_id];
    let cb = (err, data) => {
      if (!err) {
        res.json(msgJson.requestSuccess('修改角色状态'))
      } else {
        res.json(msgJson.requestFail('修改角色状态', err.sqlMessage))
      }
    }
    db.connect(sql, param, cb);

  })


/**
 * 8. 批量授权
 * @param {string} AccessIdForRole, 权限ID，required.
 * @param {array | string} roleSelectedId, 角色ID，required. [1,2],或者是'[]'
 */
router.route("/addAccessToRole")
  .post((req, res) => {
    // console.log(req.body)
    let checkResult = msgJson.checkParam(req.body, ['AccessIdForRole', 'roleSelectedId']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }
    // 先删除所有角色的权限,再重新添加
    let { AccessIdForRole, roleSelectedId } = req.body;
    if (roleSelectedId === '[]') {

      let sql = 'delete from roleaccess where acid= ?;'
      let params = [AccessIdForRole]
      let cb = (err) => {
        console.log("删除权限:", err)
        if (!err) {
          res.json(msgJson.requestSuccess('批量授权'))
        } else {
          res.json(msgJson.requestFail('批量授权'))
        }
      }
      db.connect(sql, params, cb);

    } else {
      new Promise((resolve, reject) => {
        let sql = 'delete from roleaccess where acid= ?;'
        let params = [AccessIdForRole]
        let cb = (err) => {
          if (!err) {
            resolve('')
          } else {
            reject('')
          }
        }
        db.connect(sql, params, cb);
      })
        .then(async () => {

          let sql = 'insert into roleaccess (rid, acid) values ';
          let param = [];


          for (let i = 0; i < roleSelectedId.length; i++) {
            sql += '(?,?),'
            param.push(parseInt(roleSelectedId[i]))
            param.push(parseInt(AccessIdForRole))
          }
          sql = sql.slice(0, sql.length - 1) + ';';
          // console.log("批量授权sql:", sql)

          let cb = (err) => {
            console.log("批量授权", err)
            if (err === null) {
              res.json(msgJson.requestSuccess('批量授权'))
            } else {
              console.log(err)
              res.json(msgJson.requestFail('批量授权'))
            }
          }
          db.connect(sql, param, cb)

        })

    }


  })


/**
 * 9. 获取一个权限,对应的已授权角色的列表数据
 * @param {string} AccessIdForRole, 权限ID，required.
 * @returns {array} 
 */
router.route('/getRoleForAccess')
  .get((req, res) => {
    // console.log(",,,,,", req.query)
    let checkResult = msgJson.checkParam(req.query, ['AccessIdForRole']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }
    let sql = 'select * from roleaccess where acid= ?;'
    let params = [parseInt(req.query.AccessIdForRole)];
    let cb = (err, data) => {
      if (!err) {
        res.json(msgJson.requestSuccess('获取一个权限已授权数据', data))
      } else {
        res.json(msgJson.requestFail('获取一个权限已授权数据'))
      }
    }
    db.connect(sql, params, cb)
  })

// 设置或删除一个角色对应的成员
router.route('/addUserToRole')
  .post((req, res) => {
    let checkResult = msgJson.checkParam(req.body, ['selectRoleId', 'userSelectedId']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }
    // 先删除所有角色的成员,再重新添加
    let { selectRoleId, userSelectedId } = req.body;
    if (userSelectedId === '[]') {

      let sql = 'delete from userroles where rid= ?;'
      let params = [selectRoleId]
      let cb = (err) => {
        if (!err) {
          res.json(msgJson.requestSuccess('操作角色成员'))
        } else {
          res.json(msgJson.requestFail('操作角色成员'))
        }
      }
      db.connect(sql, params, cb);

    } else {
      new Promise((resolve, reject) => {
        let sql = 'delete from userroles where rid= ?;'
        let params = [selectRoleId]
        let cb = (err) => {
          console.log("error!!", err)
          if (err === null) {
            console.log('ok')
            resolve('ok')
          } else {
            console.log('err')
            reject(err)
          }
        }
        db.connect(sql, params, cb);
      })
        .then((data) => {
          console.log('data---', data)
          let sql = 'insert into userroles (rid, uid) values ';
          let param = [];
          for (let i = 0; i < userSelectedId.length; i++) {
            sql += '(?,?),'
            param.push(parseInt(selectRoleId))
            param.push(parseInt(userSelectedId[i]))
          }
          sql = sql.slice(0, sql.length - 1) + ';';
          const cb = (err) => {
            if (!err) {
              res.json(msgJson.requestSuccess('批量设置成员'))
            } else {
              res.json(msgJson.requestFail('批量设置成员'))
            }
          }
          db.connect(sql, param, cb)

        })

    }

  })

// 设置或删除一个角色对应的权限
router.route('/addAccessForRole')
  .post((req, res) => {
    let checkResult = msgJson.checkParam(req.body, ['selectRoleId', 'accessSelectedId']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }
    // 先删除所有角色的成员,再重新添加
    let { selectRoleId, accessSelectedId } = req.body;
    if (accessSelectedId === '[]') {

      let sql = 'delete from roleaccess where rid= ?;'
      let params = [selectRoleId]
      let cb = (err) => {
        console.log("'删除角色的权限':", err)
        if (!err) {
          res.json(msgJson.requestSuccess('删除角色的权限'))
        } else {
          res.json(msgJson.requestFail('删除角色的权限'))
        }
      }
      db.connect(sql, params, cb);
    } else {

      new Promise((resolve, reject) => {
        let sql = 'delete from roleaccess where rid= ?;'
        let params = [selectRoleId]
        let cb = (err) => {
          if (!err) {
            resolve('')
          } else {
            reject('')
          }
        }
        db.connect(sql, params, cb);
      })
        .then(async () => {
          let sql = 'insert into roleaccess (rid, acid) values ';
          let param = [];
          for (let i = 0; i < accessSelectedId.length; i++) {
            sql += '(?,?),'
            param.push(parseInt(selectRoleId))
            param.push(parseInt(accessSelectedId[i]))

          }
          sql = sql.slice(0, sql.length - 1) + ';';
          console.log("批量设置成员sql:", sql)

          let cb = (err) => {
            // console.log("批量设置成员", err)
            if (err === null) {
              console.log('批量设置角色的权限成功！')
              res.json(msgJson.requestSuccess('批量设置角色的权限'))
            } else {
              console.log(err)
              res.json(msgJson.requestFail('批量设置角色的权限'))
            }
          }
          db.connect(sql, param, cb)
        })
    }
  })

// 通过1个角色ID，获取所有的关联用户
router.route('/getUsersForOneRole')
  .get((req, res) => {
    let checkResult = msgJson.checkParam(req.query, ['rid']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }

    const {rid} = req.query;
    const sql = 'select * from useraccess where rid = ?;'
    const param = [rid]
    const cb = (err,data)=>{
      if(!err){
        res.json(msgJson.requestSuccess('获取1个角色所有的关联权限'),data)
      }else{
        res.json(msgJson.requestFail('获取1个角色所有的关联权限'))
      }
    }
    db.connect(sql, param, cb)

  })
// 通过1个角色ID，获取所有的关联权限
router.route('/getAccessForOneRole')
  .get((req, res) => {
    let checkResult = msgJson.checkParam(req.query, ['rid']);
    if (checkResult) {
      res.json(checkResult)
      return;
    }

    const {rid} = req.query;
    const sql = 'select * from roleaccess where rid = ?;'
    const param = [rid]
    const cb = (err,data)=>{
      if(!err){
        res.json(msgJson.requestSuccess('获取1个角色所有的关联用户'),data)
      }else{
        res.json(msgJson.requestFail('获取1个角色所有的关联用户'))
      }
    }
    db.connect(sql, param, cb)

  })